package com.wangyadong.hobby.schedule.jobtask.linkedlist;


/**
 * <p>
 *
 * @author <714037465@qq.com>
 * @since 2018/7/318:44
 **/
public class ArrayList<E> implements List<E> {
    private int size;
    private E[] elements;
    private static final int CAPCITY = 5;

    public ArrayList() {
        elements = (E[]) new Object[CAPCITY];
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size() == 0;
    }

    @Override
    public E get(int i) throws IndexOutOfBoundsException {
        if (i > size())
            throw new IndexOutOfBoundsException("");
        return elements[i];
    }

    @Override
    public E set(int i) throws IndexOutOfBoundsException {
        return null;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int j = 0; j < elements.length; j++) {
            if (null != elements[j])
                stringBuilder.append(elements[j]).append(" ");
        }
        return stringBuilder.toString();
    }

    @Override
    public void add(E object) throws IndexOutOfBoundsException {
        //首先判断下标
        int i = size();
        if (size() + 1 > elements.length) {
            elements = resize(CAPCITY * 5);
        }
        elements[this.size] = object;
        //最后增加size
        this.size++;
    }

    @Override
    public E remove(int i) throws IndexOutOfBoundsException {
        checkIndex(i);
        E e = get(i);
        elements[i] = null;
        for (int k = i; k < size; k++) {
            elements[k] = elements[k + 1];
        }
        size--;
        return e;
    }

    private void checkIndex(int index) {
        if (index > size()) {
            throw new IndexOutOfBoundsException("can't greater than size");
        }
    }

    private E[] resize(int capcity) {
        Object[] data = new Object[capcity];
        for (int k = 0; k < elements.length; k++) {
            data[k] = elements[k];
        }
        elements = (E[]) data;
        return (E[]) data;
    }

    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        arrayList.add(1);
        arrayList.add(2);
        arrayList.add(3);
        arrayList.add(4);
        arrayList.add(5);
        arrayList.add(6);
        arrayList.add(7);
        arrayList.add(8);
        arrayList.add(9);
        arrayList.add(10);

        System.out.println(arrayList.toString());
        System.out.println(arrayList.get(3));
        System.out.println(arrayList.remove(3));
        System.out.println(arrayList.toString());
        System.out.println(arrayList.size());
    }
}
